package com.dt.platform.hr.service.impl;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dt.platform.constants.enums.common.ValidStatusEnum;

import com.dt.platform.constants.enums.hr.PaperQuestionTypeEnum;
import com.dt.platform.constants.enums.hr.PersonDataExportColumnEnum;
import com.dt.platform.constants.enums.hr.PersonUserExportColumnEnum;
import com.dt.platform.domain.hr.PaperQuestion;
import com.dt.platform.domain.hr.meta.LearnPaperMeta;
import com.dt.platform.hr.common.ResetOnCloseInputStream;
import com.dt.platform.hr.service.IPaperQuestionService;
import com.dt.platform.proxy.common.TplFileServiceProxy;
import com.github.foxnic.commons.bean.BeanNameUtil;
import com.github.foxnic.commons.bean.BeanUtil;
import com.github.foxnic.commons.lang.StringUtil;
import com.github.foxnic.commons.log.Logger;
import com.github.foxnic.commons.reflect.EnumUtil;
import com.github.foxnic.dao.data.Rcd;
import com.github.foxnic.dao.data.RcdSet;
import com.github.foxnic.dao.excel.*;
import com.github.foxnic.sql.expr.*;
import org.apache.poi.ss.usermodel.*;
import org.github.foxnic.web.domain.pcm.CatalogAttribute;
import org.github.foxnic.web.domain.system.DictItem;
import org.github.foxnic.web.domain.system.DictItemVO;
import org.github.foxnic.web.proxy.system.DictItemServiceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.foxnic.dao.entity.ReferCause;
import com.github.foxnic.commons.collection.MapUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;


import com.dt.platform.domain.hr.LearnPaper;
import com.dt.platform.domain.hr.LearnPaperVO;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.dao.data.PagedList;
import com.github.foxnic.dao.entity.SuperService;
import com.github.foxnic.dao.spec.DAO;
import java.lang.reflect.Field;
import com.github.foxnic.commons.busi.id.IDGenerator;
import com.github.foxnic.api.error.ErrorDesc;

import java.io.InputStream;
import com.github.foxnic.sql.meta.DBField;
import com.github.foxnic.dao.data.SaveMode;
import com.github.foxnic.dao.meta.DBColumnMeta;
import com.dt.platform.hr.service.ILearnPaperService;
import org.github.foxnic.web.framework.dao.DBConfigs;

/**
 * <p>
 * 课程题库服务实现
 * </p>
 * @author 金杰 , maillank@qq.com
 * @since 2024-09-14 11:34:58
*/


@Service("HrLearnPaperService")

public class LearnPaperServiceImpl extends SuperService<LearnPaper> implements ILearnPaperService {

	@Autowired
	IPaperQuestionService paperQuestionService;

	/**
	 * 注入DAO对象
	 * */
	@Resource(name=DBConfigs.PRIMARY_DAO) 
	private DAO dao=null;

	/**
	 * 获得 DAO 对象
	 * */
	public DAO dao() { return dao; }



	@Override
	public Object generateId(Field field) {
		return IDGenerator.getSnowflakeIdString();
	}

	/**
	 * 添加，根据 throwsException 参数抛出异常或返回 Result 对象
	 *
	 * @param learnPaper  数据对象
	 * @param throwsException 是否抛出异常，如果不抛出异常，则返回一个失败的 Result 对象
	 * @return 结果 , 如果失败返回 false，成功返回 true
	 */
	@Override
	public Result insert(LearnPaper learnPaper,boolean throwsException) {

		Result r=super.insert(learnPaper,throwsException);
		if(r.isSuccess()){
			dao.execute("update hr_paper_question set paper_id=? where paper_id=?",learnPaper.getId(),learnPaper.getSelectedCode());

			String sql="update hr_learn_paper set \n" +
					"total_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 ),\n" +
					"judge_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='judge'),\n" +
					"radio_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='radio'),\n" +
					"choice_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='choice'),\n" +
					"textarea_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='textarea')\n" +
					"where id=?";
			dao.execute(sql,learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId());
		}
		return r;
	}

	@Override
	public Result<JSONObject> validQuestion(String id) {


		LearnPaper learnPaper=this.getById(id);

		String sql="update hr_learn_paper set \n" +
				"total_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 ),\n" +
				"judge_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='judge'),\n" +
				"radio_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='radio'),\n" +
				"choice_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='choice'),\n" +
				"textarea_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='textarea')\n" +
				"where id=?";
		dao.execute(sql,learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId());


		dao.fill(learnPaper).with(LearnPaperMeta.PAPER_QUESTION_LIST).execute();
		List<PaperQuestion> questionList=learnPaper.getPaperQuestionList();
		JSONObject r=new JSONObject();
		r.put("questionCnt",questionList.size());
		JSONArray notPassList=new JSONArray();
		for(int i=0;i<questionList.size();i++){
			Result res=paperQuestionService.validQuestion(questionList.get(i).getId());
			if(!res.isSuccess()){
				notPassList.add(BeanUtil.toJSONObject(questionList.get(i)));
			}
		}
		r.put("questionValidNotPassCnt",notPassList.size());
		r.put("notPassList",notPassList);

		Result<JSONObject> res=new Result<JSONObject>();
		res.success();
		res.data(r);
		return res;
	}

	/**
	 * 添加，如果语句错误，则抛出异常
	 * @param learnPaper 数据对象
	 * @return 插入是否成功
	 * */
	@Override
	public Result insert(LearnPaper learnPaper) {
		return this.insert(learnPaper,true);
	}

	/**
	 * 批量插入实体，事务内
	 * @param learnPaperList 实体数据清单
	 * @return 插入是否成功
	 * */
	@Override
	public Result insertList(List<LearnPaper> learnPaperList) {
		return super.insertList(learnPaperList);
	}

	
	/**
	 * 按主键删除课程题库
	 *
	 * @param id 主键
	 * @return 删除是否成功
	 */
	public Result deleteByIdPhysical(String id) {
		LearnPaper learnPaper = new LearnPaper();
		if(id==null) return ErrorDesc.failure().message("id 不允许为 null 。");
		learnPaper.setId(id);
		try {
			boolean suc = dao.deleteEntity(learnPaper);
			return suc?ErrorDesc.success():ErrorDesc.failure();
		}
		catch(Exception e) {
			Result r= ErrorDesc.failure();
			r.extra().setException(e);
			return r;
		}
	}
	
	/**
	 * 按主键删除课程题库
	 *
	 * @param id 主键
	 * @return 删除是否成功
	 */
	public Result deleteByIdLogical(String id) {
		LearnPaper learnPaper = new LearnPaper();
		if(id==null) return ErrorDesc.failure().message("id 不允许为 null 。");
		learnPaper.setId(id);
		learnPaper.setDeleted(true);
		learnPaper.setDeleteBy((String)dao.getDBTreaty().getLoginUserId());
		learnPaper.setDeleteTime(new Date());
		try {
			boolean suc = dao.updateEntity(learnPaper,SaveMode.NOT_NULL_FIELDS);
			return suc?ErrorDesc.success():ErrorDesc.failure();
		}
		catch(Exception e) {
			Result r= ErrorDesc.failure();
			r.extra().setException(e);
			return r;
		}
	}

	/**
	 * 更新，如果执行错误，则抛出异常
	 * @param learnPaper 数据对象
	 * @param mode 保存模式
	 * @return 保存是否成功
	 * */
	@Override
	public Result update(LearnPaper learnPaper , SaveMode mode) {
		return this.update(learnPaper,mode,true);
	}

	/**
	 * 更新，根据 throwsException 参数抛出异常或返回 Result 对象
	 * @param learnPaper 数据对象
	 * @param mode 保存模式
	 * @param throwsException 是否抛出异常，如果不抛出异常，则返回一个失败的 Result 对象
	 * @return 保存是否成功
	 * */
	@Override
	public Result update(LearnPaper learnPaper , SaveMode mode,boolean throwsException) {
		Result r=super.update(learnPaper , mode , throwsException);
		if(r.isSuccess()){
			String sql="update hr_learn_paper set \n" +
					"total_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 ),\n" +
					"judge_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='judge'),\n" +
					"radio_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='radio'),\n" +
					"choice_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='choice'),\n" +
					"textarea_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='textarea')\n" +
					"where id=?";
			dao.execute(sql,learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId(),learnPaper.getId());
		}
		return r;
	}

	/**
	 * 更新实体集，事务内
	 * @param learnPaperList 数据对象列表
	 * @param mode 保存模式
	 * @return 保存是否成功
	 * */
	@Override
	public Result updateList(List<LearnPaper> learnPaperList , SaveMode mode) {
		return super.updateList(learnPaperList , mode);
	}

	
	/**
	 * 按主键更新课程题库
	 *
	 * @param id 主键
	 * @return 是否更新成功
	 */
	public boolean update(DBField field,Object value , String id) {
		if(id==null) throw new IllegalArgumentException("id 不允许为 null ");
		if(!field.table().name().equals(this.table())) throw new IllegalArgumentException("更新的数据表["+field.table().name()+"]与服务对应的数据表["+this.table()+"]不一致");
		int suc=dao.update(field.table().name()).set(field.name(), value).where().and("id = ? ",id).top().execute();
		return suc>0;
	}

	
	/**
	 * 按主键获取课程题库
	 *
	 * @param id 主键
	 * @return LearnPaper 数据对象
	 */
	public LearnPaper getById(String id) {
		LearnPaper sample = new LearnPaper();
		if(id==null) throw new IllegalArgumentException("id 不允许为 null ");
		sample.setId(id);
		return dao.queryEntity(sample);
	}

	/**
	 * 等价于 queryListByIds
	 * */
	@Override
	public List<LearnPaper> getByIds(List<String> ids) {
		return this.queryListByIds(ids);
	}

	@Override
	public List<LearnPaper> queryListByIds(List<String> ids) {
		return super.queryListByUKeys("id",ids);
	}

	@Override
	public Map<String, LearnPaper> queryMapByIds(List<String> ids) {
		return super.queryMapByUKeys("id",ids, LearnPaper::getId);
	}



	/**
	 * 查询实体集合，默认情况下，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @return 查询结果
	 * */
	@Override
	public List<LearnPaper> queryList(LearnPaperVO sample) {
		return super.queryList(sample);
	}


	/**
	 * 分页查询实体集，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @param pageSize 分页条数
	 * @param pageIndex 页码
	 * @return 查询结果
	 * */
	@Override
	public PagedList<LearnPaper> queryPagedList(LearnPaperVO sample, int pageSize, int pageIndex) {
		return super.queryPagedList(sample, pageSize, pageIndex);
	}

	/**
	 * 分页查询实体集，字符串使用模糊匹配，非字符串使用精确匹配
	 *
	 * @param sample  查询条件
	 * @param condition 其它条件
	 * @param pageSize 分页条数
	 * @param pageIndex 页码
	 * @return 查询结果
	 * */
	@Override
	public PagedList<LearnPaper> queryPagedList(LearnPaper sample, ConditionExpr condition, int pageSize, int pageIndex) {
		return super.queryPagedList(sample, condition, pageSize, pageIndex);
	}

	public ExcelStructure buildExcelStructure(InputStream dataInputStream, String code) {
		InputStream inputStream= TplFileServiceProxy.api().getTplFileStreamByCode(code);
		ExcelStructure es=new ExcelStructure();
		//	es.setDataColumnBegin(0);
		es.setDataRowBegin(2);
		Short lastNum=0;
		//从模板获取属性
		Workbook workbook;
		if ( inputStream != null) {
			try {
				workbook = WorkbookFactory.create(inputStream);
				Sheet sheet=workbook.getSheetAt(0);
				Row firstRow=sheet.getRow(0);
				Row secondRow=sheet.getRow(1);
				lastNum=firstRow.getLastCellNum();
				String charIndex="";
				for(int i=0;i<secondRow.getLastCellNum();i++){
					String asset_column=secondRow.getCell(i).toString().replaceFirst("\\{\\{\\$fe:","")
							.replaceFirst("dataList","")
							.replaceFirst("}}","")
							.replaceFirst("t.","").trim();

					String rAssetColumn="";
					//filter
					if(PersonUserExportColumnEnum.USE_USER_NAME.code().equals(asset_column)
							||PersonUserExportColumnEnum.MANAGER_NAME.code().equals(asset_column)
							||PersonUserExportColumnEnum.STATUS_NAME.code().equals(asset_column)){
						continue;
					}
					rAssetColumn= EnumUtil.parseByCode(PersonDataExportColumnEnum.class,asset_column)==null?
							BeanNameUtil.instance().depart(asset_column):
							EnumUtil.parseByCode(PersonDataExportColumnEnum.class,asset_column).text();
					Logger.info("asset_column:"+asset_column+",rAssetColumn:"+rAssetColumn);
					charIndex= ExcelUtil.toExcel26(i);
					Logger.info("cell:"+charIndex+","+secondRow.getCell(i)  +","+ firstRow.getCell(i)+","+asset_column+","+rAssetColumn);
					Logger.info("addColumn:"+rAssetColumn+","+firstRow.getCell(i).toString()+ ","+ ExcelColumn.STRING_CELL_READER);
					es.addColumn(charIndex,rAssetColumn,firstRow.getCell(i).toString(), ExcelColumn.STRING_CELL_READER);
				}
				//追加自定义属性部分
			} catch (Exception e) {
				Logger.debug("Excel 读取错误", e);
				return es;
			}
		}
		return es;
	}


	@Override
	public InputStream buildExcelTemplate(String code) {
		InputStream inputStream= TplFileServiceProxy.api().getTplFileStreamByCode(code);
		Workbook workbook;
		if(inputStream!=null){
			try {
				BufferedInputStream bufferInput = new ResetOnCloseInputStream(inputStream);
				workbook = WorkbookFactory.create(bufferInput);
				CellStyle cs=workbook.createCellStyle();
				cs.setAlignment(HorizontalAlignment.CENTER);
				cs.setVerticalAlignment(VerticalAlignment.CENTER);
				Sheet sheet=workbook.getSheetAt(0);
				Row firstRow=sheet.getRow(0);
				Row secondRow=sheet.getRow(1);
				Logger.info("SheetName:"+sheet.getSheetName());
				Logger.info("firstRow lastCellNum:"+firstRow.getLastCellNum());
				Logger.info("lastSecondRow lastCellNum:"+secondRow.getLastCellNum());
				Logger.info("lastSecondRow lastCellNum Value:"+secondRow.getCell(secondRow.getLastCellNum()-1));
//				if(firstRow.getLastCellNum()!=secondRow.getLastCellNum()){
//					return null;
//				}
				Short lastNum=firstRow.getLastCellNum();
			} catch (Exception e) {
				Logger.debug("Excel 读取错误", e);
			}
		}
		return inputStream;
	}

	@Override
	public List<ValidateResult> importExcel(InputStream input, int sheetIndex, String code,String id) {
		List<ValidateResult> errors=new ArrayList<>();
		ExcelReader er=null;
		try {
			er=new ExcelReader(input);
		} catch (Exception e) {
			errors.add(new ValidateResult(null,-1,"缺少文件"));
			return errors;
		}
		//构建 Excel 结构
		ExcelStructure es=buildExcelStructure(input,code);

		//装换成记录集
		RcdSet rs=null;
		try {
			Logger.info("sheetIndex"+sheetIndex+","+es+"ind:"+es.getColumnReadEndIndex());
			rs=er.read(sheetIndex,es);

		} catch (Exception e) {
			Logger.error("Excel 导入错误",e);
			errors.add(new ValidateResult(null,-1,"Excel 读取失败"));
			return errors;
		}
		return importData(rs,id);
	}

	public HashMap<String,String> queryDictItemDataByDictCode(String dictCode){
		HashMap<String,String> map=new HashMap<>();
		DictItemVO vo=new DictItemVO();
		vo.setDictCode(dictCode);
		Result<List<DictItem>> result= DictItemServiceProxy.api().queryList(vo);
		if(result.isSuccess()){
			List<DictItem> list=result.getData();
			for(int i=0;i<list.size();i++){
				Logger.info(dictCode+" put data:"+list.get(i).getCode()+","+list.get(i).getLabel());
				map.put(list.get(i).getCode(),list.get(i).getLabel());
			}
		}else{
		}
		return map;
	}


	public String queryMapKeyByValue(HashMap<String,String> map, String value){
		String key = null;
		//Map,HashMap并没有实现Iteratable接口.不能用于增强for循环.
		for(String getKey: map.keySet()){
			if(map.get(getKey).equals(value)){
				key = getKey;
				return key;
			}
		}
		return key;
	}


	public List<ValidateResult> importData(RcdSet rs,String id) {

		List<ValidateResult> errors=new ArrayList<>();
		Logger.info("import question id:"+id);
		HashMap<String,String> itemsMap=new HashMap<>();
		itemsMap.put("A","itemA");
		itemsMap.put("B","itemB");
		itemsMap.put("C","itemC");
		itemsMap.put("D","itemD");
		itemsMap.put("E","itemE");
		itemsMap.put("F","itemF");
		itemsMap.put("G","itemG");
		List<SQL> sqls=new ArrayList<>();

		HashMap<String,HashMap<String,String>> dictDataMap=new HashMap<>();
		dictDataMap.put("hr_question_level",queryDictItemDataByDictCode("hr_question_level"));

		HashMap<String,String> dictColumns=new HashMap<>();
		dictColumns.put("questionLevel","hr_question_level,题目难度");

		for(int i=0;i<rs.size();i++) {
			Rcd rcd =rs.getRcd(i);
			Logger.info("import question::"+rcd.toJSONObject().toJSONString());
			String questionId=rcd.getString("questionId");
			String questionName=rcd.getString("questionName");
			String questionType=rcd.getString("questionType","");
			String answer=rcd.getString("answer");
			String score=rcd.getString("score","0");
			//答案不能为空
			if(StringUtil.isBlank(answer)){
				errors.add(new ValidateResult(null,(i+1),"答案不能为空"));
				continue;
			}
			JSONArray answerArray=JSONArray.parseArray(answer);
			if(answerArray.size()==0){
				errors.add(new ValidateResult(null,(i+1),"答案不能为空"));
				continue;
			}
			//继续判断题型
			String questionTypeCode="";
			if(PaperQuestionTypeEnum.JUDGE.text().equals(questionType)){
				if(answerArray.size()!=1){
					errors.add(new ValidateResult(null,(i+1),"判断题答案只能有一个"));
					continue;
				}
				questionTypeCode=PaperQuestionTypeEnum.JUDGE.code();
			}else if(PaperQuestionTypeEnum.RADIO.text().equals(questionType)){
				if(answerArray.size()!=1){
					errors.add(new ValidateResult(null,(i+1),"判断题答案只能有一个"));
					continue;
				}
				questionTypeCode=PaperQuestionTypeEnum.RADIO.code();
			}else if(PaperQuestionTypeEnum.CHOICE.text().equals(questionType)){
				questionTypeCode=PaperQuestionTypeEnum.CHOICE.code();
			}else if(PaperQuestionTypeEnum.TEXTAREA.text().equals(questionType)){
				questionTypeCode=PaperQuestionTypeEnum.TEXTAREA.code();
			}else{
				errors.add(new ValidateResult(null,(i+1),"该题型不支持:"+questionType));
				continue;
			}
			String questionStatusName=rcd.getString("questionStatusName");
			String questionAnalysis=rcd.getString("questionAnalysis");

			String questionStatus="";
			if(StringUtil.isBlank(questionStatusName)){
				errors.add(new ValidateResult(null,(i+1),"问题状态不能为空"));
				continue;
			}

			if(ValidStatusEnum.VALID.text().equals(questionStatusName)){
				questionStatus= ValidStatusEnum.VALID.code();
			}else if(ValidStatusEnum.INVALID.text().equals(questionStatusName)){
				questionStatus= ValidStatusEnum.INVALID.code();
			}else{
				errors.add(new ValidateResult(null,(i+1),"问题状态填写错误为空"));
				continue;
			}


			HashMap<String,String> map=dictDataMap.get("hr_question_level");
			String levelName=rcd.getString("levelName");
			String level="";
			if(!StringUtil.isBlank(levelName)){
				if(map.containsValue(levelName)){
					level=queryMapKeyByValue(map,levelName);
				}else{
					errors.add(new ValidateResult(null,(i+1),"未找到题目难度。内容:"+levelName));
					break;
				}
			}

			//处理题目，支持JUDGE，RADIO，CHOICE
			String qId="";
			if(StringUtil.isBlank(questionId)){
				qId=IDGenerator.getSnowflakeIdString();
				Insert insert=new Insert("hr_paper_question");
				insert.set("id",qId);
				insert.set("name",questionName);
				insert.set("paper_id",id);
				insert.set("status",questionStatus);
				insert.set("question_type",questionTypeCode);
				insert.setIf("question_level",level);
				insert.setIf("question_analysis",questionAnalysis);
				insert.setIf("score",score);
				sqls.add(insert);
			}else{
				qId=questionId;
				Update update=new Update("hr_paper_question");
				update.set("name",questionName);
				update.set("paper_id",id);
				update.set("question_type",questionTypeCode);
				update.set("status",questionStatus);
				update.setIf("question_level",level);
				update.setIf("question_analysis",questionAnalysis);
				update.setIf("score",score);
				update.where().and("id=?",questionId);
				sqls.add(update);
				Delete delete=new Delete("hr_paper_question_item");
				delete.where().and("question_id=?",questionId);
				sqls.add(delete);
			}

			//处理选项
			String finalQId = qId;
			itemsMap.entrySet().stream().forEach((entry) -> {
				Logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
				String questionContent=rcd.getString(entry.getValue(),"");
				if(!StringUtil.isBlank(questionContent)){
					Insert insert=new Insert("hr_paper_question_item");
					insert.set("id",IDGenerator.getSnowflakeId());
					insert.set("question_id", finalQId);
					insert.set("content",questionContent);
					insert.set("code",entry.getKey());
					if(answerArray.contains(entry.getKey())){
						insert.set("selected","right");
					}else{
						insert.set("selected","wrong");
					}
					sqls.add(insert);
				}
			});
		}
		//如果存在错误，则返回错误，不存在，则运行SQL
		if(errors.size()==0){
			for(SQL sql:sqls){
				dao.execute(sql);
			}
			String sql="update hr_learn_paper set \n" +
					"total_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 ),\n" +
					"judge_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='judge'),\n" +
					"radio_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='radio'),\n" +
					"choice_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='choice'),\n" +
					"textarea_cnt=(select count(1) from hr_paper_question where paper_id=? and deleted=0 and question_type='textarea')\n" +
					"where id=?";
			dao.execute(sql,id,id,id,id,id,id);
		}
		return errors;

	}


		/**
         * 检查 实体 是否已经存在 , 判断 主键值不同，但指定字段的值相同的记录是否存在
         *
         * @param learnPaper 数据对象
         * @return 判断结果
         */
	public Boolean checkExists(LearnPaper learnPaper) {
		//TDOD 此处添加判断段的代码
		//boolean exists=super.checkExists(learnPaper, SYS_ROLE.NAME);
		//return exists;
		return false;
	}

	/**
	 * 批量检查引用
	 * @param ids  检查这些ID是否又被外部表引用
	 * */
	@Override
	public <T> Map<T, ReferCause> hasRefers(List<T> ids) {
		// 默认无业务逻辑，返回此行；有业务逻辑需要校验时，请修改并使用已注释的行代码！！！
		return MapUtil.asMap(ids,new ReferCause(false));
		// return super.hasRefers(FoxnicWeb.BPM_PROCESS_INSTANCE.FORM_DEFINITION_ID,ids);
	}





}